<template>
  <div class="main_box" style="padding-right:10px">
    <div class="add_wrap">
      <div class="tit">
        <h2>{{ dataForm.aedId ? "编辑除颤仪" : "新增除颤仪" }}</h2>
        <el-button
          type="success"
          plain
          size="small"
          icon="fa fa-mail-forward"
          @click="returnList"
          >返回</el-button
        >
      </div>
      <el-form
        :model="dataForm"
        ref="dataForm"
        label-width="200px"
        :rules="roleRules"
      >
        <el-row>
          <!-- <el-form-item prop="type" label="除颤仪类型">
              <el-select
                v-model="dataForm.type"
                placeholder="请选择除颤仪类型"
                clearable
              >
                <el-option
                  v-for="item in aedTypeList"
                  :value="item.id"
                  :label="item.name"
                  :key="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item> -->
          <el-form-item label="除颤仪名称" prop="name">
            <el-input
              v-model="dataForm.name"
              @keydown.native="keydown($event)"
            ></el-input>
          </el-form-item>
          <el-form-item label="除颤仪编号" prop="code">
            <el-input v-model="dataForm.code"></el-input>
          </el-form-item>
          <el-form-item label="除颤仪厂家编号" prop="sn">
            <el-input v-model="dataForm.sn"></el-input>
          </el-form-item>
          <el-form-item label="门磁设备" prop="doorEquipId">
            <el-select v-model="dataForm.doorEquipId" clearable>
              <el-option
                v-for="item in doorEquipList"
                :value="item.id"
                :label="item.name"
                :key="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="地区" prop="streetIds">
            <Region
              ref="region"
              :streetValues="dataForm.streetIds"
              @regionChange="handleItemChange"
              :isChangeOnSelect="true"
            ></Region>
          </el-form-item>
          <el-form-item label="小区" prop="villageId">
            <el-select
              v-model="dataForm.villageId"
              @change="handleVillageChange"
              @focus="handleVillageFocus"
              clearable
            >
              <el-option
                v-for="item in villageList"
                :value="item.id"
                :label="item.name"
                :key="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="栋单元层" prop="residentAddress">
            <el-cascader
              v-model="dataForm.residentAddress"
              :props="{ value: 'id', label: 'name',checkStrictly: true }"
              :options="residentAddressList"
              clearable
              filterable
              placeholder="请选择栋单元层"
            ></el-cascader>
          </el-form-item>
          <!-- <el-form-item label="门牌号" prop="houseNumber">
            <el-input v-model="dataForm.houseNumber"></el-input>
          </el-form-item> -->
          <el-form-item label="经度" prop="longitude">
            <el-input type="number" v-model="dataForm.longitude"></el-input>
          </el-form-item>
          <el-form-item label="纬度" prop="latitude">
            <el-input type="number" v-model="dataForm.latitude"></el-input>
            <el-button type="text" @click="getLngLat(1)">百度地图</el-button>
            <el-button type="text" @click="getLngLat(2)">腾讯地图</el-button>
          </el-form-item>
          <el-form-item prop="siteUrl" label="位置图">
            <upload-img
              class="upload-img"
              @uploadFileList="getsiteUrl"
              folder="aedSitefile"
            >
              <img
                v-if="dataForm.siteUrl"
                width="100%"
                :src="dataForm.siteUrl"
                alt=""
              />
              <div class="tip">
                <i class="el-icon-upload" v-if="!dataForm.siteUrl"></i>
                <div v-if="!dataForm.siteUrl" class="el-upload__text">
                  将图片拖到此处，或<em>点击上传</em>
                </div>
              </div>
            </upload-img>
          </el-form-item>
          <!-- <el-form-item label="时间点" prop="timePoints">
              <el-select v-model="dataForm.timePoints" multiple clearable filterable placeholder="最多可以选择五个时间">
                <el-option v-for="item in timeList" :key="item.value" :value="item.value" :label="item.label" :disabled="item.disabled">
                </el-option>
              </el-select>
            </el-form-item> -->
        </el-row>
        <!-- <el-row v-show="dataForm.type == 1">
            <div class="tit">
              <h2>关联商户</h2>
              <el-button
                @click="addRelationBusiness"
                circle
                type="success"
                icon="el-icon-plus"
              >
              </el-button>
            </div>
            <el-table
              :data="dataForm.list"
              style="width:fit-content;margin-top:10px"
            >
              <el-table-column align="center" width="100" label="操作">
                <template slot-scope="scope">
                  <el-button
                    @click="subRelationBusiness(scope.$index)"
                    plain
                    type="danger"
                    circle
                    icon="el-icon-minus"
                  >
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column align="center" width="300" label="商户">
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.businessId"
                    @change="businessChange(scope.row)"
                    clearable
                    filterable
                  >
                    <el-option
                      v-for="item in businessList"
                      :label="item.name"
                      :value="item.id"
                      :key="item.id"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align="center" width="300" label="部门">
                <template slot-scope="scope">
                  <el-cascader
                    style="width:250px"
                    @focus="getDepartList(scope.row)"
                    v-model="scope.row.departId"
                    :options="scope.row.departList"
                    :props="{
                      label: 'departName',
                      value: 'departId',
                      checkStrictly: true
                    }"
                    clearable
                    filterable
                  >
                  </el-cascader>
                </template>
              </el-table-column>
            </el-table>
          </el-row> -->
        <el-row>
          <el-form-item>
            <el-button plain type="primary" @click="sureClick">保 存</el-button>
            <el-button plain @click="returnList">取 消</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import * as message from "@/constants/message";
import AedApi from "@/api/equip/aed";
import DepartApi from "@/api/business/depart";
import BusinessApi from "@/api/business/business";
import Region from "@/components/Region";
import VillageAreaApi from "@/api/address/villageArea";
import VillageApi from "@/api/address/village";
import UploadImg from "@/components/UploadImg";
export default {
  name: "AedAdd",
  components: {
    Region,
    UploadImg
  },
  data() {
    return {
      dataForm: {
        type: 1,
        aedId: "",
        name: "",
        code: "",
        sn: "",
        provinceId: "",
        provinceName: "",
        cityId: "",
        cityName: "",
        areaId: "",
        areaName: "",
        streetIds: [],
        streetName: "",
        villageId: "",
        doorEquipId: "",
        villageName: "",
        residentAddress: [], // 栋单元层
        houseNumber: "",
        longitude: "",
        latitude: "",
        siteUrl: "",
        // timePoints:[],
        list: [
          {
            businessId: "",
            departId: [],
            departList: []
          }
        ]
      },
      residentAddressList: [],
      villageList: [], //小区列表
      doorEquipList: [{ id: 1, name: "关" }, { id: 2, name: "开" }],
      timeList: [],
      departList: [],
      aedTypeList: [{ id: 1, name: "商户" }, { id: 2, name: "平台" }],
      businessList: [],
      roleRules: {
        type: [
          { required: true, message: "请选择除颤仪类型", trigger: "change" }
        ],
        name: [
          { required: true, message: "请输入除颤仪名称", trigger: "blur" }
        ],
        sn: [
          { required: true, message: "请输入除颤仪厂家编号", trigger: "blur" }
        ],
        code: [
          { required: true, message: "请输入除颤仪编号", trigger: "blur" }
        ],
        streetIds: [
          { required: true, message: "请选择地区", trigger: "change" }
        ],
        villageId: [
          { required: true, message: "请选择小区", trigger: "change" }
        ],
        residentAddress: [
          { required: true, message: "请选择栋单元层", trigger: "change" }
        ],
        houseNumber: [
          { required: true, message: "请输入门牌号", trigger: "blur" }
        ],
        doorEquipId: [
          { required: true, message: "请选择门磁设备", trigger: "change" }
        ]
      }
    };
  },
  watch: {
    // "dataForm.timePoints":{
    //   handler(val){
    //     if(val.length==5){
    //       this.timeList.forEach(item=>{
    //         if(!val.includes(item.value)){
    //           this.$set(item,"disabled",true)
    //         }else{
    //           this.$delete(item,"disabled")
    //         }
    //       })
    //     }else{
    //       this.timeList.forEach(item=>this.$delete(item,"disabled"))
    //     }
    //   },
    //   immediate:true
    // }
  },
  mounted() {
    this.init();
    this.getDoorlinklist()
  },
  methods: {
    init() {
      this.getBusinessList();
      // this.getFiveIntTime();
      if (this.$route.query.id) {
        this.dataForm.aedId = this.$route.query.id;
        this.getData();
      }
    },
    keydown(e) {
      if (e.keyCode == 32) {
        e.returnValue = false;
      }
    },
    async getData() {
      const cond = {
        id: this.dataForm.aedId
      };
      const res2 = await AedApi.getAedInfo(cond);
      this.$Utils.bindingBean(this.dataForm, res2.data);
      this.dataForm.streetIds = [
        this.dataForm.provinceId,
        this.dataForm.provinceName,
        this.dataForm.cityId,
        this.dataForm.cityName,
        this.dataForm.areaId,
        this.dataForm.areaName,
        this.dataForm.streetId,
        this.dataForm.streetName
      ];
      // await this.getDepartList();

      // this.formatData(res2.data);

      if (res2.data.villageId) {
        this.villageList = [
          { id: res2.data.villageId, name: res2.data.villageName }
        ];
        this.dataForm.residentAddress = [
          res2.data.buildId,
          res2.data.unitId,
          res2.data.floorId,
          res2.data.houseNumberId
        ].filter(item => item);
        this.getResidentAddressList();
      }
    },
    getDoorlinklist() {
      AedApi.doorlinkList().then(res => {
        this.doorEquipList = res.data;
      });
    },
    /**
     *  获取全部是5整数的时间数组
     */

    // getFiveIntTime() {
    //   let maxHours = 0;
    //   do {
    //     const val = maxHours > 9 ? "" + maxHours : "0" + maxHours;
    //     let maxMinutes = 0;
    //     do {
    //       const val2 = maxMinutes > 9 ? "" + maxMinutes : "0" + maxMinutes;
    //       const val3 = val + ":" + val2;
    //       this.timeList.push({ value: val3, label: val3 });
    //       maxMinutes = maxMinutes + 5;
    //     } while (maxMinutes < 60);
    //     maxHours++;
    //   } while (maxHours < 24);
    // },
    formatData(data) {
      data.list.forEach(item => {
        if (item.departId) {
          let val = this.$Utils.filterTreeToArr(
            this.departList,
            item,
            "departId"
          );
          val = JSON.parse(JSON.stringify(val));
          item.departId = [];
          item.departList = [];
          val.forEach((item2, index) => {
            item.departId.push(item2.departId);
            if (index == 0) {
              item.departList = [item2];
            } else {
              let children = val[index - 1].children;
              children ? children.push(item2) : (children = [item2]);
            }
          });
        }
      });
      // data.timePoints = data.timePoints?data.timePoints.split(","):[]
    },
    getBusinessList() {
      BusinessApi.listIdNameVo().then(res => {
        this.businessList = res.data;
      });
    },
    addRelationBusiness() {
      this.dataForm.list.push({
        businessId: "",
        departId: "",
        departList: []
      });
    },
    subRelationBusiness(index) {
      this.dataForm.list.splice(index, 1);
    },
    businessChange(row) {
      row.departId = [];
      row.departList = [];
      this.getBusinessList();
    },
    // async getDepartList(row) {
    //   const params = {};
    //   if (row && !row.businessId) {
    //     return;
    //   } else if (row && row.businessId) {
    //     params.businessId = row.businessId;
    //   }
    //   const res = await DepartApi.listMangerTree(params);
    //   if (row) {
    //     if (row.hasOwnProperty("departList")) {
    //       row.departList = res.data;
    //     } else {
    //       this.$set(row, "departList", res.data);
    //     }
    //   } else {
    //     this.departList = res.data;
    //   }
    // },
    // checkData() {
    //   let { type, list } = this.dataForm;
    //   if (type == 1) {
    //     this.dataForm.list = list = list.filter(item => item.businessId);
    //     if (!list.length) {
    //       this.$message.error("请至少添加一个关联商户");
    //       return;
    //     }

    //     this.list = list.map(item => {
    //       const obj = Object.assign(
    //         {},
    //         { ...item },
    //         {
    //           departLevel: (item.departId && item.departId.length) || "",
    //           departId: (item.departId && item.departId.at(-1)) || ""
    //         }
    //       );
    //       delete obj.departList;
    //       return obj;
    //     });
    //   }
    //   return true;
    // },
    // 通过小区获取栋单元层下的数据
    async getResidentAddressList() {
      const { data } = await VillageAreaApi.getListTree({
        villageId: this.dataForm.villageId
      });
      this.residentAddressList = data || [];
    },
    handleItemChange(val) {
      // 地区改变要清空小区和设备地址还有列表
      this.dataForm.villageId = "";
      this.dataForm.villageName = "";
      this.villageList = [];
      this.dataForm.provinceId = val.provinceId;
      this.dataForm.provinceName = val.provinceName;
      this.dataForm.cityId = val.cityId;
      this.dataForm.cityName = val.cityName;
      this.dataForm.areaId = val.areaId;
      this.dataForm.areaName = val.areaName;
      this.dataForm.streetId = val.streetId;
      this.dataForm.streetName = val.streetName;
      this.dataForm.residentAddress = null;
      this.residentAddressList = [];

      if (val.provinceId) {
        // 如果地区是删除那么就不用删除列表和设备地址数据
        // this.dataForm.beeperBtnList.forEach(item => {
        //   item.businessIdList = []
        //   item.businessList = []
        //   item.btnGoodsParams = []
        // })
        this.dataForm.streetIds = [
          val.provinceId,
          val.cityId,
          val.areaId,
          val.streetId
        ];
      } else {
        this.dataForm.streetIds = [];
      }
    },
    handleVillageChange() {
      this.dataForm.villageName = "";
      this.dataForm.residentAddress = [];
      this.residentAddressList = [];

      if (!this.dataForm.villageId) return;
      // if (this.dataForm.villageId) {
      this.dataForm.villageName = this.villageList.find(
        item => item.id == this.dataForm.villageId
      ).name;
      this.getResidentAddressList();
    },
    handleVillageFocus() {
      // 点击聚焦小区的时候才发送请求数据
      if (this.dataForm.streetIds.length > 0) {
        let param = {
          provinceId: this.dataForm.provinceId,
          cityId: this.dataForm.cityId,
          areaId: this.dataForm.areaId,
          streetId: this.dataForm.streetId,
          name: ""
        };
        VillageApi.villageList(param).then(res => {
          this.villageList = res.data;
        });
      }
    },
    getLngLat(type) {
      if (type == 1) {
        window.open(
          "https://api.map.baidu.com/lbsapi/getpoint/index.html",
          "_blank"
        );
      } else {
        window.open("https://lbs.qq.com/getPoint", "_blank");
      }
    },
    sureClick() {
      // 提交
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          // if (!this.checkData()) return;
          this.$confirm(
            message.MSG_CONFIRM_SAVE_ALTER,
            message.TITLE_PROMPT,
            {}
          ).then(() => {
            if (this.dataForm.aedId) {
              this.editData();
            } else {
              this.addData();
            }
          });
        }
      });
    },
    editData() {
      let { residentAddress } = this.dataForm;
      // 这里处理以下楼栋单元层的地址
      this.residentAddress = this.$Utils.filterTreeToArr(
        this.residentAddressList,
        { id: residentAddress.at(-1) },
        "id"
      );
      // 编辑
      var cond = {
        aedId: this.dataForm.aedId,
        type: this.dataForm.type,
        name: this.dataForm.name,
        sn: this.dataForm.sn,
        code: this.dataForm.code,
        siteUrl: this.dataForm.siteUrl,
        houseNumber: this.dataForm.houseNumber,
        longitude: this.dataForm.longitude,
        latitude: this.dataForm.latitude,
        provinceId: this.dataForm.provinceId,
        provinceName: this.dataForm.provinceName,
        cityId: this.dataForm.cityId,
        cityName: this.dataForm.cityName,
        areaId: this.dataForm.areaId,
        areaName: this.dataForm.areaName,
        streetId: this.dataForm.streetId,
        streetName: this.dataForm.streetName,
        villageId: this.dataForm.villageId,
        villageName: this.dataForm.villageName,
        buildId: this.residentAddress[0]?.id,
        buildName: this.residentAddress[0]?.name,
        unitId: this.residentAddress[1]?.id,
        unitName: this.residentAddress[1]?.name,
        floorId: this.residentAddress[2]?.id,
        floorName: this.residentAddress[2]?.name,
        houseNumberId: this.residentAddress[3]?.id,
        houseNumber: this.residentAddress[3]?.name,
        doorEquipId: this.dataForm.doorEquipId
        // timePoints:this.dataForm.timePoints.length?this.dataForm.timePoints.join(","):"",
        // list: this.dataForm.type == 1 ? this.list : []
      };
      AedApi.editAed(cond).then(data => {
        this.$Utils.notifySuccess();
        this.returnList();
      });
    },
    addData() {
      // 新增
      let { residentAddress } = this.dataForm;
      // 这里处理以下楼栋单元层的地址
      this.residentAddress = this.$Utils.filterTreeToArr(
        this.residentAddressList,
        { id: residentAddress.at(-1) },
        "id"
      );
      var cond = {
        type: this.dataForm.type,
        name: this.dataForm.name,
        sn: this.dataForm.sn,
        siteUrl: this.dataForm.siteUrl,
        code: this.dataForm.code,
        houseNumber: this.dataForm.houseNumber,
        longitude: this.dataForm.longitude,
        latitude: this.dataForm.latitude,
        provinceId: this.dataForm.provinceId,
        provinceName: this.dataForm.provinceName,
        cityId: this.dataForm.cityId,
        cityName: this.dataForm.cityName,
        areaId: this.dataForm.areaId,
        areaName: this.dataForm.areaName,
        streetId: this.dataForm.streetId,
        streetName: this.dataForm.streetName,
        villageId: this.dataForm.villageId,
        villageName: this.dataForm.villageName,
        buildId: this.residentAddress[0]?.id,
        buildName: this.residentAddress[0]?.name,
        unitId: this.residentAddress[1]?.id,
        unitName: this.residentAddress[1]?.name,
        floorId: this.residentAddress[2]?.id,
        floorName: this.residentAddress[2]?.name,
        houseNumberId: this.residentAddress[3]?.id,
        houseNumber: this.residentAddress[3]?.name,
        doorEquipId: this.dataForm.doorEquipId
        // timePoints:this.dataForm.timePoints.length?this.dataForm.timePoints.join(","):"",
        // list: this.dataForm.type == 1 ? this.list : []
      };
      AedApi.addAed(cond).then(data => {
        this.$Utils.notifySuccess();
        this.returnList();
      });
    },
    returnList() {
      this.$store.dispatch("delView", this.$route);
      this.$router.push({ path: "/equip/aedManagement" });
    },
    getsiteUrl(val) {
      if (val.length > 0) {
        this.$Utils.notifySuccess("上传成功");
      }
      this.dataForm.siteUrl = val[0];
    }
  }
};
</script>

<style lang="scss" scoped>
@import "@/assets/css/views/add.scss";
.upload-img {
  &::v-deep .el-upload {
    width: 100%;

    .el-upload-dragger {
      width: 100%;
      display: flex;
      justify-content: space-around;
      align-items: center;

      .tip {
        padding-bottom: 30px;
      }
    }
  }
}
</style>
<style lang="scss"></style>
